const db=wx.cloud.database();
// pages/clock/clock.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // time:"",
    // ipvalue:"",
    // listArr:[]
    time:"",
    timeColumns: [
      Array.from({ length: 24 }, (_, i) => i.toString().padStart(2, '0')), // 小时 (00-23)
      Array.from({ length: 60 }, (_, i) => i.toString().padStart(2, '0')), // 分钟 (00-59)
      Array.from({ length: 60 }, (_, i) => i.toString().padStart(2, '0')), // 秒 (00-59)
    ],
    timeIndex: [0, 0, 0], // 默认选中 [0时, 0分, 0秒]
    selectedTime: "00:00:00",
    listArr: [],
  },

// 添加到已有 Page 结构中即可
setQuickCountdown(e) {
  const seconds = Number(e.currentTarget.dataset.seconds);
  const h = Math.floor(seconds / 3600).toString().padStart(2, '0');
  const m = Math.floor((seconds % 3600) / 60).toString().padStart(2, '0');
  const s = (seconds % 60).toString().padStart(2, '0');
  const selectedTime = `${h}:${m}:${s}`;
  
  this.setData({
    selectedTime,
    time: seconds
  });

  db.collection("daojishi").add({
    data: { daojishi: selectedTime }
  }).then(() => {
    wx.showToast({ title: "快捷添加成功", icon: "none" });
    this.sendOpenCommand();
  });
},




  columnChange(e) {
    const { column, value } = e.detail;
    const newIndex = [...this.data.timeIndex];
    newIndex[column] = value;
    this.setData({ timeIndex: newIndex });
  },

  timepick(e) {
    const [hour, minute, second] = this.data.timeIndex.map(
      (index, i) => this.data.timeColumns[i][index]
    );
    const selectedTime = `${hour}:${minute}:${second}`;
    
    this.setData({ selectedTime });

    db.collection("daojishi").add({
      data: { daojishi: selectedTime }
    }).then(res => {
      wx.showToast({ title: "添加成功", icon: "none" });
      console.log(this.data.selectedTime);
      const totalSeconds = this.hhmmssToSeconds(this.data.selectedTime); // 转换为秒
      console.log(totalSeconds);
      this.setData({
        time:totalSeconds
      })
      this.sendOpenCommand();
    });
  },

   hhmmssToSeconds(timeStr) {
    const [hours, minutes, seconds] = timeStr.split(':').map(Number);
    return hours * 3600 + minutes * 60 + seconds;
  },
/**
     * 获取token按钮按下：
     */
    gettoken(){
      // console.log("开始获取。。。");//打印完整消息
      var that=this;  //这个很重要，在下面的回调函数中由于异步问题不能有效修改变量，需要用that获取
      wx.request({
        url: 'https://iam.cn-north-4.myhuaweicloud.com/v3/auth/tokens',
        data: {
          "auth": {
            "identity": {
              "methods": [
                "password"
              ],
              "password": {
                "user": {
                  "domain": {
                    "name": "GT-2301_81266702"
                  },
                  "name": "GT-2301_81266702",
                  "password": "Lmcindy6388"
                }
              }
            },
            "scope": {
              "project": {
                "name": "cn-east-3"
              }
            }
          }
        },
        method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
        header: {'content-type': 'application/json' }, // 请求的 header 
        success: function(res){// success
          // success
            console.log("获取token成功");//打印完整消息
            //console.log(res);//打印完整消息
            var token='';
token=JSON.stringify(res.header['X-Subject-Token']);//解析消息头token
token=token.replaceAll("\"", "");
//console.log("获取token=\n"+token);//打印token
wx.setStorageSync('token',token);//把token写到缓存中,以便可以随时随地调用
        },
        fail:function(){
            // fail
            console.log("获取token失败");//打印完整消息
        },
        complete: function() {
            // complete
            console.log("获取token完成");//打印完整消息
        } 
    });
    },
// 发送倒计时命令
sendOpenCommand() {
  console.log("开始下发命令...");
  const that = this;
  const token = wx.getStorageSync('token');

  wx.request({
    url: 'https://92aad16b61.st1.iotda-app.cn-east-3.myhuaweicloud.com:443/v5/iot/72dbf1784ff04685985c53fba5220913/devices/6810ab2d3878983101479033_smart_pill_box_lm/commands',
    data: {
      "service_id": "get_data",
      "command_name": "set_daojishi",
      "paras": {
        "countdown": this.data.time
      }
    
    },
    method: 'POST',
    header: {
      'content-type': 'application/json',
      'X-Auth-Token': token
    },
    success: function(res) {
      console.log("下发命令成功");
      //console.log(res);
       // 关键修复：检查状态码
       if (res.statusCode !== 200) {
        console.error("命令下发失败，状态码:", res.statusCode);
        that.setData({ checked: false });
        wx.showToast({ title: '失败:设备可能离线', icon: 'none' });
        return; // 终止后续逻辑
      }
    },
    fail: function(err) {
      console.log("命令下发失败");
      console.log("请先获取token");
      that.setData({ checked: false }); // 失败时也复位
      wx.showToast({ title: '失败', icon: 'none' });
    },
    complete: function() {
      console.log("命令下发完成");
      that.setData({ result: '设备命令下发完成' });
    }
  });
},


//   timepick(picker){
//     let arr=this.data.listArr;
// console.log(picker);
// db.collection("daojishi").add({
//   data:{
//     daojishi:picker.detail.value
//   }
// }).then(res=>{
//   console.log(picker.detail.value);
//   wx.showToast({
//         title:"添加成功",
//         icon:"none"
//       })
// })
//   },
columnChange(e) {
  const { column, value } = e.detail;
  const newIndex = [...this.data.timeIndex];
  newIndex[column] = value;
  this.setData({ timeIndex: newIndex });
},

// timepick(e) {
//   const [hour, minute, second] = this.data.timeIndex.map(
//     (index, i) => this.data.timeColumns[i][index]
//   );
//   const selectedTime = `${hour}:${minute}:${second}`;
  
//   this.setData({ selectedTime });

//   db.collection("daojishi").add({
//     data: { daojishi: selectedTime }
//   }).then(res => {
//     wx.showToast({ title: "添加成功", icon: "none" });
//   });
// },


get(){
db.collection("daojishi").get().then(res=>{
  //console.log(res.data);
  this.setData({
    listArr:res.data
  })
})
},
//点击关闭列表按钮
clickclose(e){
  console.log(e.currentTarget.dataset.index);
  wx.showModal({
    title: '是否确认删除',
    success:res=>{
      db.collection("daojishi").doc(e.currentTarget.dataset.index).remove().then(() => {
        wx.showToast({ title: "删除成功", icon: "success" });
        this.get(); // 重新加载列表
      }).catch(err => {
        console.error("删除失败：", err);
      });
    }
  })
},
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.gettoken();

this.get();
db.collection("daojishi").watch({
  onChange:res=>{
    this.get();
  },
  onError:err=>{
    console.log(err);
  }
})
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
this.get();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})